<template>
  <Head :title="`${keyword ? keyword + ' - ' : ''}搜索结果`" />
  <ShopLayout>
    <div class="bg-gray-50 min-h-screen">
      <div class="max-w-7xl mx-auto px-8 sm:px-16 lg:px-24 py-12">
        <!-- 搜索信息 -->
        <div v-if="keyword" class="mb-8">
          <h1 class="text-3xl font-light text-gray-900 mb-2">
            搜索 "<mark class="bg-yellow-100 px-1">{{ keyword }}</mark>"
          </h1>
          <p class="text-gray-600">
            找到 {{ products.meta?.total || 0 }} 个相关产品
          </p>
        </div>

        <!-- 无搜索词时显示热门搜索 -->
        <div v-else class="text-center py-16">
          <svg class="mx-auto h-16 w-16 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <h3 class="text-xl font-light text-gray-900 mb-2">请输入搜索关键词</h3>
          <p class="text-gray-600 mb-8">或尝试以下热门搜索</p>
          
          <div v-if="hotSearches.length > 0" class="flex flex-wrap justify-center gap-2 mt-6">
            <Link
              v-for="item in hotSearches"
              :key="item.id"
              :href="route('search.index', { q: item.keyword })"
              class="px-4 py-2 bg-white rounded-full text-sm text-gray-700 hover:bg-gray-100 transition-colors shadow-sm"
            >
              {{ item.keyword }}
            </Link>
          </div>
        </div>

        <!-- 有搜索结果时 -->
        <div v-if="keyword && products.data && products.data.length > 0">
          <!-- 筛选和排序栏 -->
          <div class="flex items-center justify-between mb-6 pb-6 border-b border-gray-200">
            <div class="flex items-center gap-4">
              <!-- 分类筛选 -->
              <select
                v-model="currentFilters.category_id"
                @change="applyFilters"
                class="px-4 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900"
              >
                <option value="">全部分类</option>
                <option v-for="category in availableCategories" :key="category.id" :value="category.id">
                  {{ category.name }}
                </option>
              </select>

              <!-- 价格筛选 -->
              <select
                v-model="currentFilters.price_range"
                @change="applyPriceFilter"
                class="px-4 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900"
              >
                <option value="">全部价格</option>
                <option value="0-1000">¥0 - ¥1,000</option>
                <option value="1000-5000">¥1,000 - ¥5,000</option>
                <option value="5000-10000">¥5,000 - ¥10,000</option>
                <option value="10000-">¥10,000以上</option>
              </select>
            </div>

            <!-- 排序 -->
            <select
              v-model="currentFilters.sort"
              @change="applyFilters"
              class="px-4 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900"
            >
              <option value="">综合排序</option>
              <option value="price_asc">价格从低到高</option>
              <option value="price_desc">价格从高到低</option>
              <option value="newest">最新上架</option>
            </select>
          </div>

          <!-- 产品网格 -->
          <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-12">
            <div
              v-for="product in products.data"
              :key="product.id"
              class="group bg-white rounded-2xl overflow-hidden hover:shadow-xl transition-shadow duration-300"
            >
              <Link :href="route('product.show', product.slug)" class="block">
                <div class="aspect-square bg-gray-100 overflow-hidden">
                  <img
                    :src="product.image"
                    :alt="product.name"
                    class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                  />
                </div>
                <div class="p-6">
                  <h3 class="text-lg font-medium text-gray-900 mb-2 group-hover:text-gray-600 transition-colors">
                    {{ product.name }}
                  </h3>
                  <p class="text-sm text-gray-600 mb-4 line-clamp-2">{{ product.description }}</p>
                  <div class="flex items-baseline gap-2">
                    <span class="text-2xl font-light text-gray-900">¥{{ product.price.toLocaleString() }}</span>
                    <span v-if="product.compare_price" class="text-sm text-gray-500 line-through">
                      ¥{{ product.compare_price.toLocaleString() }}
                    </span>
                    <span v-if="product.discount_percentage" class="ml-auto text-xs font-semibold text-red-600">
                      省{{ product.discount_percentage }}%
                    </span>
                  </div>
                </div>
              </Link>
              <!-- 对比按钮 (暂时注释) -->
              <!-- <div class="px-6 pb-6">
                <CompareButton :product-id="product.id" class="w-full" />
              </div> -->
            </div>
          </div>

          <!-- 分页 -->
          <div v-if="products.meta && products.meta.last_page > 1" class="flex justify-center">
            <nav class="inline-flex rounded-lg shadow-sm -space-x-px" aria-label="Pagination">
              <Link
                v-for="(link, index) in products.links"
                :key="index"
                :href="link.url"
                :class="[
                  'relative inline-flex items-center px-4 py-2 text-sm font-medium',
                  link.active
                    ? 'z-10 bg-gray-900 text-white'
                    : 'bg-white text-gray-700 hover:bg-gray-50',
                  index === 0 ? 'rounded-l-lg' : '',
                  index === products.links.length - 1 ? 'rounded-r-lg' : '',
                  !link.url ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'
                ]"
                :disabled="!link.url"
                v-html="link.label"
              />
            </nav>
          </div>
        </div>

        <!-- 无搜索结果 -->
        <div v-else-if="keyword && products.data && products.data.length === 0" class="text-center py-16">
          <svg class="mx-auto h-16 w-16 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <h3 class="text-xl font-light text-gray-900 mb-2">未找到相关产品</h3>
          <p class="text-gray-600 mb-8">试试其他关键词或浏览热门搜索</p>
          
          <div v-if="hotSearches.length > 0" class="flex flex-wrap justify-center gap-2">
            <Link
              v-for="item in hotSearches"
              :key="item.id"
              :href="route('search.index', { q: item.keyword })"
              class="px-4 py-2 bg-white rounded-full text-sm text-gray-700 hover:bg-gray-100 transition-colors shadow-sm"
            >
              {{ item.keyword }}
            </Link>
          </div>
        </div>
      </div>
    </div>
  </ShopLayout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import ShopLayout from '@/Layouts/ShopLayout.vue'
import CompareButton from '@/Components/CompareButton.vue'

const props = defineProps({
  keyword: String,
  products: Object,
  filters: Object,
  hotSearches: Array
})

const currentFilters = ref({
  category_id: props.filters?.category_id || '',
  price_range: '',
  sort: props.filters?.sort || ''
})

// 从价格范围设置min_price和max_price
if (props.filters?.min_price || props.filters?.max_price) {
  const min = props.filters.min_price || 0
  const max = props.filters.max_price || ''
  if (max) {
    currentFilters.value.price_range = `${min}-${max}`
  } else {
    currentFilters.value.price_range = `${min}-`
  }
}

// 获取所有可用分类（从产品中提取）
const availableCategories = computed(() => {
  const categoriesMap = new Map()
  
  props.products?.data?.forEach(product => {
    product.categories?.forEach(category => {
      if (!categoriesMap.has(category.id)) {
        categoriesMap.set(category.id, category)
      }
    })
  })
  
  return Array.from(categoriesMap.values())
})

// 应用价格筛选
const applyPriceFilter = () => {
  const range = currentFilters.value.price_range
  let min_price = ''
  let max_price = ''
  
  if (range && range !== '') {
    const parts = range.split('-')
    min_price = parts[0] || ''
    max_price = parts[1] || ''
  }
  
  router.get(route('search.index'), {
    q: props.keyword,
    category_id: currentFilters.value.category_id || undefined,
    min_price: min_price || undefined,
    max_price: max_price || undefined,
    sort: currentFilters.value.sort || undefined
  }, {
    preserveState: true,
    preserveScroll: true
  })
}

// 应用筛选
const applyFilters = () => {
  applyPriceFilter()
}
</script>

